package com.example.simpleforum.dao;

import com.example.simpleforum.model.Post;
import com.example.simpleforum.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 帖子数据访问对象
 */
public class PostDao {
    
    /**
     * 添加新帖子
     * @param post 帖子对象
     * @return 新增帖子的ID，失败返回-1
     */
    public int addPost(Post post) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int postId = -1;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO post (title, content, user_id, forum_id, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, post.getTitle());
            pstmt.setString(2, post.getContent());
            pstmt.setInt(3, post.getUserId());
            pstmt.setInt(4, post.getForumId());
            pstmt.setTimestamp(5, post.getCreateTime());
            pstmt.setTimestamp(6, post.getUpdateTime());
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    postId = rs.getInt(1);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return postId;
    }
    
    /**
     * 更新帖子
     * @param post 帖子对象
     * @return 更新成功返回true，失败返回false
     */
    public boolean updatePost(Post post) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE post SET title = ?, content = ?, update_time = ? WHERE id = ? AND user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, post.getTitle());
            pstmt.setString(2, post.getContent());
            pstmt.setTimestamp(3, post.getUpdateTime());
            pstmt.setInt(4, post.getId());
            pstmt.setInt(5, post.getUserId());
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
    
    /**
     * 删除帖子
     * @param postId 帖子ID
     * @param userId 用户ID（确保只能删除自己的帖子）
     * @return 删除成功返回true，失败返回false
     */
    public boolean deletePost(int postId, int userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM post WHERE id = ? AND user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            pstmt.setInt(2, userId);
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
    
    /**
     * 板块管理员删除帖子
     * @param postId 帖子ID
     * @param forumId 板块ID
     * @return 删除成功返回true，失败返回false
     */
    public boolean deletePostByForumAdmin(int postId, int forumId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM post WHERE id = ? AND forum_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            pstmt.setInt(2, forumId);
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
    
    /**
     * 主管理员删除帖子
     * @param postId 帖子ID
     * @return 删除成功返回true，失败返回false
     */
    public boolean deletePostByMainAdmin(int postId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM post WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        return success;
    }
    
    /**
     * 获取帖子所属的板块ID
     * @param postId 帖子ID
     * @return 板块ID，如果帖子不存在则返回-1
     */
    public int getForumIdByPostId(int postId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int forumId = -1;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT forum_id FROM post WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, postId);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                forumId = rs.getInt("forum_id");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return forumId;
    }
    
    /**
     * 根据ID查询帖子
     * @param id 帖子ID
     * @return 帖子对象，不存在则返回null
     */
    public Post findById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Post post = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT p.*, u.username FROM post p JOIN user u ON p.user_id = u.id WHERE p.id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                post = new Post();
                post.setId(rs.getInt("id"));
                post.setTitle(rs.getString("title"));
                post.setContent(rs.getString("content"));
                post.setUserId(rs.getInt("user_id"));
                post.setUsername(rs.getString("username"));
                post.setCreateTime(rs.getTimestamp("create_time"));
                post.setUpdateTime(rs.getTimestamp("update_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return post;
    }
    
    /**
     * 查询所有帖子，按最新发布时间排序
     * @return 帖子列表
     */
    public List<Post> findAllPosts() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Post> posts = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT p.*, u.username, f.name as forum_name FROM post p " +
                       "JOIN user u ON p.user_id = u.id " +
                       "LEFT JOIN forum f ON p.forum_id = f.id " +
                       "ORDER BY p.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Post post = new Post();
                post.setId(rs.getInt("id"));
                post.setTitle(rs.getString("title"));
                post.setContent(rs.getString("content"));
                post.setUserId(rs.getInt("user_id"));
                post.setUsername(rs.getString("username"));
                post.setCreateTime(rs.getTimestamp("create_time"));
                post.setUpdateTime(rs.getTimestamp("update_time"));
                post.setForumName(rs.getString("forum_name"));
                posts.add(post);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return posts;
    }
    
    /**
     * 查询指定用户的所有帖子
     * @param userId 用户ID
     * @return 帖子列表
     */
    public List<Post> findPostsByUserId(int userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Post> posts = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT p.*, u.username FROM post p JOIN user u ON p.user_id = u.id WHERE p.user_id = ? ORDER BY p.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Post post = new Post();
                post.setId(rs.getInt("id"));
                post.setTitle(rs.getString("title"));
                post.setContent(rs.getString("content"));
                post.setUserId(rs.getInt("user_id"));
                post.setUsername(rs.getString("username"));
                post.setCreateTime(rs.getTimestamp("create_time"));
                post.setUpdateTime(rs.getTimestamp("update_time"));
                posts.add(post);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return posts;
    }
    
    /**
     * 根据板块ID查询帖子
     * @param forumId 板块ID
     * @return 帖子列表
     */
    public List<Post> findPostsByForumId(int forumId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Post> posts = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT p.*, u.username, f.name as forum_name FROM post p " +
                       "JOIN user u ON p.user_id = u.id " +
                       "LEFT JOIN forum f ON p.forum_id = f.id " +
                       "WHERE p.forum_id = ? " +
                       "ORDER BY p.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, forumId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Post post = new Post();
                post.setId(rs.getInt("id"));
                post.setTitle(rs.getString("title"));
                post.setContent(rs.getString("content"));
                post.setUserId(rs.getInt("user_id"));
                post.setForumId(rs.getInt("forum_id"));
                post.setUsername(rs.getString("username"));
                post.setCreateTime(rs.getTimestamp("create_time"));
                post.setUpdateTime(rs.getTimestamp("update_time"));
                posts.add(post);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return posts;
    }
}